<template>
  <div>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="95vw" height="90vh" append-to-body v-if="open" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" style="width: 15%;" />
        </el-form-item>
        <el-form-item label="分类名称" prop="cateId">
          <el-select v-model="form.cateId" v-el-select-scroll="handleScroll" @clear="clearSearch" @visible-change="visibleChange" filterable clearable remote reserve-keyword placeholder="请选择分类名称" :remote-method="remoteMethod">
            <el-option v-for="item in cateList" :key="item.value" :label="item.cateName" :value="item.cateId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品专区" prop="productArea">
          <el-select v-model="form.productArea" placeholder="请选择商品专区" clearable>
            <el-option
              v-for="(item, index) in productAreaList"
              :key="index"
              :label="item.areaName"
              :value="item.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="productStatus">
          <el-select v-model="form.productStatus" placeholder="请选择商品状态" clearable>
            <el-option
              v-for="(item, index) in productStatusList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="首页展示" prop="showIndexFlag">
          <el-radio-group v-model="form.showIndexFlag">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入商品排序" style="width: 15%;" />
        </el-form-item>
        <el-form-item label="封面图" ref="mainImageUrl" prop="mainImageUrl">
          <image-drap-upload v-model="form.mainImageUrl" :limit="1" :size="10" />
        </el-form-item>
        <el-form-item label="商品图片" ref="productImageUrl" prop="productImageUrl">
          <image-drap-upload v-model="form.productImageUrl" :size="10" />
        </el-form-item>
        <!-- 添加sku商品 -->
        <el-form-item label="商品规格" required>
          <div class="specBox">
            <el-button @click="addSpecNew" v-if="specNew.length != 1">添加规格</el-button>
            <!-- 规格 -->
            <div v-for="(item,index) in specNew" :key="index">
              <div>
                <el-form-item label="规格名" required>
                  <el-input v-model="item.specNewName" :value="item.specNewName" placeholder="请输入" style="width: 200px;"  @blur="changeSpecName(index)" />
                </el-form-item>
              </div>
              <div class="m-t-10">
                <el-form-item class="flex-1 flexBox" label="规格值" required>
                  <div v-for="(items,indexs) in item.specNewValue" :key="indexs" class="inputBox">
                    <el-input v-model="items.specValueName" :value="items.specValueName" placeholder="请输入" @blur="changeSpecValue(index,indexs)" />
                    <i class="el-icon-circle-close deleteBtn" @click="delSpecValue(index,indexs)"></i>
                  </div>
                  <el-button @click="addSpecValue(index)">添加规格值</el-button>
                </el-form-item>
              </div>
            </div>
            <!-- 规格详情 -->
            <el-table v-if="specNew.length != 0" :data="skuList" stripe type="expand" style="width: 100%" :default-expand-all="true" class="m-t-10">
              <el-table-column prop="specValue" label="规格" align="center">
                <template slot-scope="scope">
                  <el-input :value="scope.row.specValue" placeholder="规格值" readonly />
                </template>
              </el-table-column>
              <el-table-column prop="pic" label="规格图片" align="center">
                <template slot-scope="scope">
                  <image-drap-upload v-model="scope.row.pic" :limit="1" :size="10" />
                </template>
              </el-table-column>
              <el-table-column prop="platformPrice" label="售价" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.platformPrice" placeholder="售价" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);" />
                </template>
              </el-table-column>
              <el-table-column prop="costPrice" label="成本价" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.costPrice" placeholder="成本价" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/);" />
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.unit" maxlength="5" placeholder="单位" />
                </template>
              </el-table-column>
              <el-table-column prop="publishStatus" width="140" label="上下架状态" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.publishStatus" placeholder="上下架状态" clearable style="width:100%">
                    <el-option label="已上架" value="1" />
                    <el-option label="已下架" value="2" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="inventory" label="库存" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.inventory" :min="0" placeholder="库存" onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode || event.which))) || event.which === 8" />
                </template>
              </el-table-column>
              <el-table-column prop="expressType" width="140" label="快递类型" align="center">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.expressType" placeholder="请选择" clearable style="width:100%">
                    <el-option label="到付" value="1" />
                    <el-option label="包邮" value="2" />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="详情">
          <div style="border: 1px solid #ccc" v-if="open">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden;"
              v-model="form.productDetail"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import { productCateList } from "@/api/product/productCate";
import { insertProduct, modifyProduct } from "@/api/product/product";
import { getSassToken } from "@/utils/utils";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Debounce } from '@/utils/tools.js';
import imageDrapUpload from '@/components/Upload';
export default {
  name: "editProduct",
  props: {
    form:Object,
    title: String,
    productAreaList: Array,
    productStatusList: Array,
    productTypeList:Array,
  },
  components: {
    Editor,
    Toolbar,
    imageDrapUpload
  },
  data() {
    return {
      // 是否显示弹出层
      open: false,
      edit: false,//编辑
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        cateId: [
          { required: true, message: "请选择分类名称", trigger: "change" }
        ],
        productArea: [
          { required: true, message: "请选择商品区域", trigger: "change" }
        ],
        productStatus: [
          { required: true, message: "请选择商品状态", trigger: "change" }
        ],
        showIndexFlag:[
          { required: true, message: "请选择是否展示在首页", trigger: "change" }
        ],
        productType:[
          { required: true, message: "请选择商品类型", trigger: "change" }
        ],
        productPrice: [
          { required: true, message: "请输入价格", trigger: "blur" }
        ], 
        inventory: [
          { required: true, message: "请输入库存", trigger: "blur" }
        ],
        mainImageUrl: [
          { required: true, message: "请上传封面图", trigger: "change" }
        ],
        productImageUrl: [
          { required: true, message: "请上传商品图片", trigger: "change" }
        ],
        sort: [
          { required: true, message: "请输入商品排序", trigger: "blur" }
        ],
        pic: [
          { required: true, message: "请上传sku规格图片", trigger: "change" }
        ]
      },
      dialogImageUrl: '',
      uploadUrl: process.env.VUE_APP_UPLOAD_IMG + "/common/uploadFile",
      editor: null,
      toolbarConfig: {},
      editorConfig: { 
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            server:  process.env.VUE_APP_UPLOAD_IMG + "/common/uploadFile",
            headers: {
              Develop: 'prod',
              SaasToken: getSassToken()
            },
            fieldName: 'files',
            customInsert(res, insertFn) {
                // 上传图片
                let url = res.data && res.data[0].browseUrl || ''
                let alt = ''
                let href = res.data && res.data[0].browseUrl || ''
                insertFn(url, alt, href)
            }
          }
        }
      },
      mode: "default", // or 'simple'
      skuList:[],
      cateList: [],//分类下拉
      cateQuery:{
        pageNo: 1, 
        pageSize: 20,
      },
      cateTotal: 0,
      value:null,
      specNew:[]
    };
  },
  filters:{
    getScale(val,price){
      let scale = 0;
      if(val && price && val > 0 && price > 0){
        scale = ((Number(val) / Number(price))*100).toFixed(0)+'%'
      }
      return scale;
    }
  },
  watch:{
    open: {
      handler(newVal) {
        if(newVal){
          this.$nextTick(() => {  this.$refs['form'].clearValidate();});
          if(!this.edit) {
            this.form.productImageUrlList = []
          }
          this.loadCateData()
        }
      },
      immediate: true
    },
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
      editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
  methods: {
    // 新增规格
    addSpecNew(){
      let arr = []
      if(this.specNew.length == 0){
        let obj = {
          specNewName:'',
          specNewValue:[{specValueName:''}]
        }
        arr.push(obj)
      }
      this.specNew = arr
      this.skuList = [{
        skuName: "",//规格名
        specValue: "",//规格值
        pic: [],//图片
        platformPrice: "",//售价
        costPrice: "",//成本
        unit: "",//单位
        publishStatus: "",//上下架状态: (1-已上架 2-已下架)
        inventory: "",//库存
        expressType: '1',//快递类型 1 到付、2 包邮，默认到付
        buyCount: "",//起售量
        limitedCount: ""//限购量
      }]
    },
    // 新增规格值
    addSpecValue(index){
      this.specNew[index].specNewValue.push({specValueName:''})
      this.skuList.push({
        skuName: this.specNew[0].specNewName,//规格名
        specValue: "",//规格值
        pic: [],//图片
        platformPrice: "",//售价
        costPrice: "",//成本
        unit: "",//单位
        publishStatus: "",//上下架状态: (1-已上架 2-已下架)
        inventory: "",//库存
        expressType: '1',//快递类型 1 到付、2 包邮，默认到付
        buyCount: "",//起售量
        limitedCount: ""//限购量
      })
    },
    // 删除规格值
    delSpecValue(index,indexs){
      this.specNew[index].specNewValue.splice(indexs,1)
      this.skuList.splice(indexs,1)
    },
    // 规格名改变
    changeSpecName(index){
      let arr = JSON.parse(JSON.stringify(this.skuList))
      arr.forEach(item => {
        item.skuName = this.specNew[index].specNewName
      })
      this.skuList = arr
      this.$forceUpdate()
    },
    // 规格值改变
    changeSpecValue(index,indexs){
      let arr = JSON.parse(JSON.stringify(this.skuList))
      arr.forEach((item,ind) => {
        if(ind == indexs){
          item.specValue = this.specNew[index].specNewValue[indexs].specValueName
        }
      })
      this.skuList = arr
      this.$forceUpdate()
    },





    // 解决搜索为空，关闭下拉后再展开下拉数据为空的情况
    visibleChange(bool){
      if(bool && !this.cateList.length){
        this.cateQuery.pageNo = 1
        this.cateQuery.cateName = null
        this.loadCateData()
      }
    },
    // 搜索分类
    remoteMethod(cateName){
      if(cateName){
        this.cateQuery.pageNo = 1
        this.cateQuery.cateName = cateName
        productCateList(this.cateQuery).then(res => {
          if(res.code === 200){
            if(this.cateQuery.pageNo == 1){
              this.cateList = res.data.records;
            }else{
              this.cateList = this.cateList.concat(res.data.records)
            }
            this.cateTotal = res.data.pages;
          }
        })
      }else{
        this.cateQuery.pageNo = 1
        this.cateQuery.cateName = null
        this.loadCateData()
      }
    },
    // 清空
    clearSearch(){
        this.cateQuery.pageNo = 1
        this.cateQuery.cateName = null
        this.loadCateData()
    },
    // 滚动加载下一页
    handleScroll(param){
      if( param && this.cateQuery.pageNo < this.cateTotal){
        this.cateQuery.pageNo++
        this.loadCateData()
      }
    },
    // 分类
    loadCateData(){
      productCateList(this.cateQuery).then(res => {
        if(res.code === 200){
          if(this.cateQuery.pageNo == 1){
            this.cateList = res.data.records;
          }else{
            this.cateList = this.cateList.concat(res.data.records)
          }
          this.cateTotal = res.data.pages;
        }
      })
    },
    // 检查规格
    checkSpec(){
      let bool = false;
      if(this.skuList.length !== 0){
        try {
          this.skuList.forEach(item => {
            if(!item.skuName){
              bool = false
              this.$modal.msgError("请正确填写规格名");
              throw Error();//直接跳出循环
            }else if(!item.specValue){
              bool = false
              this.$modal.msgError("请正确填写规格值");
              throw Error();//直接跳出循环
            }else if(item.pic.length == 0){
              bool = false
              this.$modal.msgError("请上传规格图片");
              throw Error(); 
            }else if(!item.platformPrice){
              bool = false
              this.$modal.msgError("请正确填写售价");
              throw Error(); 
            }else if(!item.costPrice){
              bool = false
              this.$modal.msgError("请正确填写成本价");
              throw Error(); 
            }else if(!item.publishStatus){
              bool = false
              this.$modal.msgError("请正确选择上下架状态");
              throw Error(); 
            }else if(!item.inventory){
              bool = false
              this.$modal.msgError("请正确填写库存");
              throw Error(); 
            }else{
              bool = true
            }
          })
        } catch (e) {

        }
      }
      return bool
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$emit('reset')
    },
    /** 提交按钮 */
    submitForm:Debounce(function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {                                        
          let data = JSON.parse(JSON.stringify(this.form))
          let skuList = JSON.parse(JSON.stringify(this.skuList)) 
          let bool = this.checkSpec()
          if(bool){
            let sku = [...skuList]
            sku.forEach(item => {
              item.pic = item.pic[0].url
            })
            data.skuList = sku
            // 封面图
            if(this.form.mainImageUrl.length == 1){
              data.mainImageUrl = this.form.mainImageUrl[0].url
            }
            // 商品主图
            if(this.form.productImageUrl.length > 0){
              data.productImageUrl = this.form.productImageUrl.map(item => item.url)
            }
            if(data.productId) {
              modifyProduct(data).then((response) => {
                this.open = false;
                this.$modal.msgSuccess("操作成功");
                this.$emit('update')
              })
            } else {
              insertProduct(data).then((response) => {
                this.$modal.msgSuccess("操作成功");
                this.open = false;
                this.$emit('update')
              })
            }
          }
        }
      });
    },500),
  },
};
</script>
<style lang="scss" scoped>
.titleSpec{
  margin-left: 10px;
  font-weight: bold;
}
.m-t-10{
  margin-top: 10px;
}
.w-100{
  width: 100%;
}
.flex-1{
  flex: 1;
}
.specBox{
  flex:1;
  position: relative;
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 10px;
}
.closeBtn{
  font-size: 14px;
  font-weight: bold;
  color: red;
}
.closeSpecBtn{
  margin: 0;
  line-height: 36px;
  width: 60px;
  text-align: center;
  font-weight: bold;
  color: red;
  font-size: 14px;
}
.itemBox{
  width: 80%;
  position: relative;
}
.itemSpecBox{
  width: 100%;
  display: flex;
  position: relative;
  padding-bottom: 10px;
  border-bottom: 1px solid #e3e3e3;
}
.itemSpecBox:last-child{
  border-bottom: none;
}
::v-deep .itemSpecBox .el-form-item__label{
  width: 100px !important;
}
::v-deep .itemSpecBox .el-form-item__content{
  margin-left: 100px !important;
}

.bottomBtn{
  position: absolute;
  bottom: 10px;
  left: 20px;
}
/* 设置弹窗最大高度为500px */
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  max-height: calc(100% -  150px);
}
::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow-y: auto;
}
::v-deep .el-table__expand-column{
 // display: none !important;
}



::v-deep .flexBox .el-form-item__content{
  display: flex !important;
}
.inputBox{
  width: 120px;
  margin-right: 10px;
  position: relative;
}
.deleteBtn{
  position: absolute;
  right: -10px;
  top: -10px;
}
</style>